@echo off
chcp 65001
setlocal enabledelayedexpansion

:set_options
set "access_token="
set "message="
set "change_log="
set "env="

:parse_options
if "%~1"=="" GOTO :get_param
if /I "%~1"=="-c" set "change_log=%~2" & shift
if /I "%~1"=="-t" set "access_token=%~2" & shift
if /I "%~1"=="-m" set "message=%~2" & shift
if /I "%~1"=="-e" set "env=%~2" & shift
shift /1
GOTO :parse_options

:get_param
if "%env%"=="Release_Debug" (
    set "source=C:\mateurp_pipline\mate-client-adnroid\app\build\outputs\apk\Release_\debug"
) else (
    set "source=C:\mateurp_pipline\mate-client-adnroid\app\build\outputs\apk\Test_\debug"
)

set "apk_name="
set "destinationNAS=E:\Mate\Pipeline\mate_nas_%env%.apk"

for %%F in ("%source%\*.apk") do (
    set "apk_name=%%F"
    goto :found
)
:found
echo APK文件路径: %apk_name%
call "C:\mateurp_pipline\obsutil\rename_apk_by_time.bat" "%apk_name%"
set "apk_name=%renamed_apk_path%"
echo 重命名后APK路径: %apk_name%

:check_args
if defined apk_name if defined access_token if defined message (
    echo apk package name: %apk_name%
    echo git commit log: %change_log%
    echo access_token: %access_token%
    echo message: %message%
    echo env: %env%

    REM Upload package to Weli App
    curl.exe --location --request POST "http://appstore-admin.etouch.cn/app-store-server/api/app/pkg/latest/upload" ^
        --header "Content-Type: multipart/form-data" ^
        --form "file=@%apk_name%" --form "ver_desc=%change_log%"

    if %ERRORLEVEL% equ 0 (
        curl.exe --ssl-no-revoke  "https://oapi.dingtalk.com/robot/send?access_token=%access_token%" ^
            -H "Content-Type: application/json" ^
            -d "{\"msgtype\": \"text\",\"text\": {\"content\": \"%message%\"}}"

    ) else (
        echo Upload failed, check the response
        exit /b 1
    )

    REM Delete renamed apk file
	echo copy apk file to %destinationNAS%
	copy /Y %apk_name% %destinationNAS%

) else (
    echo Invalid arguments
    goto :usage
    exit /b 1
)

endlocal